import pygame
import random
import math

class Hamster:
    """仓鼠白芝麻类，管理回血道具的行为"""
    def __init__(self, sprite_path, screen_width, screen_height, player_speed):
        """初始化仓鼠白芝麻
        Args:
            sprite_path (str): 图片路径
            screen_width (int): 屏幕宽度
            screen_height (int): 屏幕高度
            player_speed (int): 玩家速度，用于计算仓鼠速度
        """
        # 加载精灵图并缩放至1/2大小
        original_sprite = pygame.image.load(sprite_path).convert_alpha()
        width = original_sprite.get_width() // 2
        height = original_sprite.get_height() // 2
        self.sprite = pygame.transform.scale(original_sprite, (width, height))  # 缩放图片
        self.rect = self.sprite.get_rect()  # 获取矩形区域
        self.screen_width = screen_width  # 屏幕宽度
        self.screen_height = screen_height  # 屏幕高度
        self.base_speed = player_speed * 0.5  # 基础速度为玩家速度的0.5倍
        self.escape_speed = player_speed * 1.5  # 逃跑速度为玩家速度的1.5倍
        self.escape_timer = 0  # 逃跑计时器
        self.speed = self.base_speed  # 当前速度
        self.x = random.randint(0, screen_width - self.rect.width)  # 随机x坐标
        self.y = random.randint(0, screen_height - self.rect.height)  # 随机y坐标
        self.dx = random.choice([-1, 1]) * self.speed  # 随机x方向速度
        self.dy = random.choice([-1, 1]) * self.speed  # 随机y方向速度
        self.timer = 0  # 计时器
        self.respawn_timer = 0  # 重生计时器
        self.visible = True  # 是否可见
        self.respawn_interval = 10  # 重生间隔（秒）
        self.damage = 1  # 伤害值
        self.health = 10  # 血量

    def update(self, players, current_time):
        """更新仓鼠状态
        Args:
            players (list): 玩家列表
            current_time (float): 当前时间
        """
        if self.visible:
            # 运动
            self.x += self.dx  # 更新x坐标
            self.y += self.dy  # 更新y坐标
             
            # 边界反弹
            if self.x <= 0 or self.x >= self.screen_width - self.rect.width:
                self.dx *= -1  # x方向反转
            if self.y <= 0 or self.y >= self.screen_height - self.rect.height:
                self.dy *= -1  # y方向反转
                 
            # 运动行为
            self.timer += 1/60  # 假设60 FPS
             
            # 寻找最近的玩家
            nearest_player = None
            min_dist = float('inf')
            for player in players:
                dist = math.hypot(player.x - self.x, player.y - self.y)
                if dist < min_dist:
                    min_dist = dist
                    nearest_player = player
             
            if nearest_player:
                # 计算远离最近玩家的方向
                dx = self.x - nearest_player.x
                dy = self.y - nearest_player.y
                dist = math.hypot(dx, dy)
                 
                if dist < 100:  # 小于2个身位
                    # 开始逃跑
                    self.speed = self.escape_speed  # 设置为逃跑速度
                    self.escape_timer = pygame.time.get_ticks() / 1000 + 1  # 设置逃跑计时器
                     
                    # 计算远离所有玩家的方向
                    total_dx = 0
                    total_dy = 0
                    for player in players:
                        dx = self.x - player.x
                        dy = self.y - player.y
                        dist = math.hypot(dx, dy)
                        if dist > 0:
                            total_dx += dx / dist
                            total_dy += dy / dist
                     
                    # 归一化合成方向向量
                    total_dist = math.hypot(total_dx, total_dy)
                    if total_dist > 0:
                        total_dx /= total_dist
                        total_dy /= total_dist
                         
                    # 更新移动方向
                    self.dx = total_dx * self.speed
                    self.dy = total_dy * self.speed
                elif dist > 200:  # 大于4个身位
                    # 随机移动
                    self.speed = self.base_speed * 0.5
                    if self.timer >= 1.5:  # 每1.5秒改变方向
                        self.timer = 0
                        angle = random.uniform(0, 2 * math.pi)
                        self.dx = math.cos(angle) * self.speed
                        self.dy = math.sin(angle) * self.speed
                else:
                    # 正常移动
                    self.speed = self.base_speed
                    self.dx = random.choice([-1, 1]) * self.speed
                    self.dy = random.choice([-1, 1]) * self.speed
                     
                # 检查逃跑时间是否结束
                if self.escape_timer > 0 and pygame.time.get_ticks() / 1000 >= self.escape_timer:
                    self.escape_timer = 0
                    self.speed = self.base_speed
                         
            # 更新位置并进行边界检查
            self.x = max(0, min(self.screen_width - self.rect.width, self.x))
            self.y = max(0, min(self.screen_height - self.rect.height, self.y))
            self.rect.topleft = (self.x, self.y)
             
            # 如果移动过快则进行边界反弹
            if self.x <= 0 or self.x >= self.screen_width - self.rect.width:
                self.dx *= -1
                self.x = max(0, min(self.screen_width - self.rect.width, self.x))
            if self.y <= 0 or self.y >= self.screen_height - self.rect.height:
                self.dy *= -1
                self.y = max(0, min(self.screen_height - self.rect.height, self.y))
                 
            # 碰撞检测
            for player in players:
                if self.rect.colliderect(player.rect):
                    self.apply_effect(player)  # 应用回血效果
                    self.visible = False  # 隐藏仓鼠
                    self.respawn_timer = current_time + self.respawn_interval  # 使用设置的重生间隔
                    break
        else:
            # 检查是否需要重生
            if current_time >= self.respawn_timer:
                self.respawn()  # 重生仓鼠

    def apply_effect(self, player):
        """应用回血效果
        Args:
            player (Player): 玩家对象
        """
        # 恢复50%已损失血量
        player.health = min(player.max_health,
                          player.health + (player.max_health - player.health) // 2)
         
        # 根据玩家应用特殊效果
        if player.controls['up'] == pygame.K_w:  # 玩家1（吒）
            player.attack_speed = 2.0  # 攻击速度提升至2倍
            player.attack_speed_timer = pygame.time.get_ticks() / 1000 + 5  # 持续5秒
        else:  # 玩家2（丙）
            player.reflect_damage = True  # 开启伤害反射
            player.reflect_timer = pygame.time.get_ticks() / 1000 + 5  # 持续5秒

    def respawn(self):
        """重生仓鼠"""
        self.visible = True  # 设置为可见
        self.x = random.randint(0, self.screen_width - self.rect.width)  # 随机x坐标
        self.y = random.randint(0, self.screen_height - self.rect.height)  # 随机y坐标
        self.dx = random.choice([-1, 1]) * self.speed  # 随机x方向速度
        self.dy = random.choice([-1, 1]) * self.speed  # 随机y方向速度

    def draw(self, screen):
        """绘制仓鼠
        Args:
            screen (pygame.Surface): 游戏屏幕
        """
        if self.visible:
            screen.blit(self.sprite, (self.x, self.y))  # 在指定位置绘制仓鼠